﻿using System.Net.Http.Headers;

namespace Leo.MSATracert
{
    public class LinkTracertHttpHandler : DelegatingHandler
    {
        private readonly bool tokenRelay;
        public LinkTracertHttpHandler(bool tokenRelay) : base(new HttpClientHandler())
        {
            this.tokenRelay = tokenRelay;
        }
         
        public LinkTracertHttpHandler() : this(false)
        {
        } 

        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            LinkTracertPrincipal principal = ServiceInvocationLinkTrace.GetPrincipal(null, null);
            string text = ((principal != null) ? principal.RequestId : null) ?? Guid.NewGuid().ToString("N").ToLower();
            if (!string.IsNullOrEmpty((principal != null) ? principal.IPAddress : null))
            {
                request.Headers.TryAddWithoutValidation("X-Forwarded-For", principal.IPAddress);
            }
            request.Headers.TryAddWithoutValidation("X-Sensitive", "3aed2fe84efb0f3b3106db8697060e93");
            request.Headers.UserAgent.Clear();
            request.Headers.UserAgent.Add(new ProductInfoHeaderValue("APIContract", "v1.0.0"));
            if (this.tokenRelay && principal != null && principal.TokenCollection.Count > 0)
            {
                foreach (IApiToken apiToken in principal.TokenCollection)
                {
                    if (!string.IsNullOrEmpty(apiToken.Name) && !string.IsNullOrEmpty(apiToken.Value))
                    {
                        request.Headers.TryAddWithoutValidation(apiToken.Name, apiToken.Value);
                    }
                }
            }
            request.Headers.TryAddWithoutValidation("X-Connection-Id", text);
            return base.SendAsync(request, cancellationToken);
        }
         
       
    }
}
